import { DeleteOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tooltip } from 'antd';
import type { SearchFieldConfig } from '../types';

/**
 * 检查必填字段是否已填写
 * @param searchFields 搜索字段配置
 * @param params 参数对象
 * @returns 是否所有必填字段都已填写
 */
export const checkRequiredFields = (
  searchFields: SearchFieldConfig[] | undefined,
  params: Record<string, any> = {},
): boolean => {
  if (!searchFields) return true;

  const requiredFields = searchFields.filter((field) => field.required);
  const missingFields = requiredFields.filter((field) => {
    const value = params[field.name];
    return value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);
  });

  return missingFields.length === 0;
};

/**
 * 操作按钮配置接口
 */
export interface ActionButtonConfig {
  key: string;
  label?: string;
  icon: React.ReactNode;
  danger?: boolean;
  type?: 'primary' | 'default' | 'link';
  className?: string;
  permission?: string; // 对应权限字段，如 'view', 'update', 'delete'
  disabled?: boolean | ((record: any) => boolean); // 禁用状态，可以是布尔值或根据行数据判断的函数
}
/**
 * 国际化辅助工具
 * 直接从全局状态获取当前语言，避免 React Hook 的闭包问题
 */

import { getIntl, getLocale } from 'umi';

/**
 * 获取翻译文本
 * @param prefix 前缀，如 'systemManage'
 * @param key 键名，如 'resourceId'
 * @param params 参数对象，用于替换 {key} 占位符
 * @returns 翻译后的文本
 */
export const t = (prefix: string, key: string, params?: Record<string, any>): string => {
  try {
    const intl = getIntl();
    const locale = getLocale();

    // 检查 intl 是否可用
    if (!intl || !intl.formatMessage) {
      return `${prefix}.${key}`; // 返回 key 本身作为降级方案
    }

    const id = `${prefix}.${key}`;
    let text = intl.formatMessage({ id }) || id;

    // 如果有参数，进行模板替换
    if (params) {
      Object.entries(params).forEach(([paramKey, value]) => {
        text = text.replace(`{${paramKey}}`, String(value));
      });
    }

    return text;
  } catch (error) {
    return `${prefix}.${key}`;
  }
};

/**
 * 构建操作列配置
 * @param permissions 权限配置
 * @param onAction 统一的操作回调函数，参数为 (actionType: string, record: T)
 * @param customActions 自定义操作按钮配置（可选，不传则使用默认按钮）
 * @returns ProTable 操作列配置
 */
export const buildActionColumn = <T = any,>(
  permissions: Record<string, boolean>,
  onAction: (actionType: string, record: T) => void,
  customActions?: ActionButtonConfig[],
): ProColumns<T> => {
  // 默认操作按钮配置
  const defaultActions: ActionButtonConfig[] = [
    {
      key: 'view',
      label: '详情',
      icon: <EyeOutlined />,
      type: 'link',
      className: 'page-template-action-detail-btn',
      permission: 'view',
    },
    {
      key: 'edit',
      label: '编辑',
      icon: <EditOutlined />,
      type: 'link',
      className: 'page-template-action-edit-btn',
      permission: 'update',
    },
    {
      key: 'delete',
      label: '删除',
      icon: <DeleteOutlined />,
      type: 'link',
      danger: true,
      className: 'page-template-action-delete-btn',
      permission: 'delete',
    },
  ];

  // 使用自定义操作或默认操作
  const actions = customActions || defaultActions;

  return {
    title: t('common', 'operation'),
    dataIndex: 'operation',
    valueType: 'option',
    width: actions.length > 3 ? actions.length * 40 : 120,
    fixed: 'right',
    render: (_, record) => (
      <Space>
        {actions
          .filter((action) => !action.permission || permissions[action.permission])
          .map((action) => {
            // 判断按钮是否禁用
            let isDisabled = false;
            if (action.disabled !== undefined) {
              if (typeof action.disabled === 'boolean') {
                isDisabled = action.disabled;
              } else if (typeof action.disabled === 'function') {
                isDisabled = action.disabled(record);
              }
            }

            return (
              <Tooltip key={action.key} title={action.label}>
                <Button
                  type={action.type || 'link'}
                  size="small"
                  danger={action.danger}
                  icon={action.icon}
                  disabled={isDisabled}
                  onClick={() => onAction(action.key, record)}
                  className={action.className}
                />
              </Tooltip>
            );
          })}
      </Space>
    ),
  };
};

/**
 * 批量操作按钮配置接口
 */
export interface BatchActionConfig {
  key: string;
  label: string;
  icon?: React.ReactNode;
  danger?: boolean;
  type?: 'primary' | 'default';
  className?: string;
  action: (selectedRows: any[]) => Promise<void> | void;
}

/**
 * 构建批量操作按钮组
 * @param selectedRowKeys 选中的行键
 * @param selectedRows 选中的行数据
 * @param actions 批量操作配置数组
 * @returns 批量操作按钮组
 */
export const buildBatchActions = (
  selectedRowKeys: React.Key[],
  selectedRows: any[],
  actions: BatchActionConfig[],
): React.ReactNode => {
  return (
    <>
      {actions.map((action) => (
        <Button
          key={action.key}
          type={action.type}
          danger={action.danger}
          icon={action.icon}
          onClick={() => action.action(selectedRows)}
          className={
            action.className ||
            (action.danger ? 'page-template-toolbar-danger-btn' : 'page-template-toolbar-normal-btn')
          }
        >
          {action.label} ({selectedRowKeys.length})
        </Button>
      ))}
    </>
  );
};
